<?php

namespace two;
require_once __DIR__ . '/../vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;

/**
 * 死信队列实战
 */
class Consumer01
{
    // 普通交换机的名称
    public static $normalExchange = 'normal_exchange';
    // 死信交换机的名称
    public static $deadExchange = 'dead_exchange';
    // 普通队列名称
    public static $normalQueue = 'normal_queue';
    // 死信队列名称
    public static $deadQueue = 'dead_queue';

    // 过期时间
    public static $ttl = 10;

    public function __construct()
    {
        self::consumer01();
    }

    public static function consumer01()
    {
        $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
        $channel = $connection->channel();
        // 声明死信和普通交换机 类型微direct
        $channel->exchange_declare(self::$normalExchange, 'direct', false, false, false);
        $channel->exchange_declare(self::$deadExchange, 'direct', false, false, false);

        // 声明普通队列
        // 死信消息 设置TTL时间 time to live
        // 正常队列设置死信交换机
        $argument = new AMQPTable([
            // 'x-message-ttl' => self::$ttl * 1000,
            'x-dead-letter-exchange' => self::$deadExchange,
            'x-dead-letter-routing-key' => 'PHP-Dead-Key',
            'x-max-length' => 6
        ]);


        $channel->queue_declare(self::$normalQueue, false, true, false, false, false, $argument);

        /*************************************************************************************************/
        // 声明死信和普通队列
        $channel->queue_declare(self::$deadQueue, false, true, false, false);
        // 绑定普通的交换机与普通队列
        $channel->queue_bind(self::$normalQueue, self::$normalExchange, 'PHP-Key');
        // 绑定死信的交换机与死信队列
        $channel->queue_bind(self::$deadQueue, self::$deadExchange, 'PHP-Dead-Key');

        $callback = function ($msg) use ($channel) {
            if ($msg->body = 'info5') {
                // 消息被拒绝，放入死信队列
                $channel->basic_reject($msg->delivery_info['delivery_tag'], false);
            } else {
                echo " [x] Received ", $msg->body, "\n";
                $channel->basic_ack($msg->delivery_info['delivery_tag'], false);
            }
        };

        $channel->basic_consume(self::$normalQueue, '', false, false, false, false, $callback);
    }

    /*
    public static function ()
    {

    }*/
}


new Consumer01();